﻿using System.Windows;
using System.Windows.Controls;


namespace ibba.src.noriskbo.code
{
    public class TextBoxUpdateManager
    {
        public static readonly DependencyProperty UpdateOnPropertyChangedProperty =
            DependencyProperty.RegisterAttached("UpdateOnPropertyChanged", typeof(bool), typeof(TextBoxUpdateManager),
                    new PropertyMetadata(new PropertyChangedCallback(UpdateOnPropertyChangedPropertyCallback)));

        public static bool GetUpdateOnPropertyChanged(DependencyObject obj)
        {
            return (bool)obj.GetValue(UpdateOnPropertyChangedProperty);
        }

        public static void SetUpdateOnPropertyChanged(DependencyObject obj, bool value)
        {
            obj.SetValue(UpdateOnPropertyChangedProperty, value);
        }
        
        private static void UpdateOnPropertyChangedPropertyCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is TextBox)
            {
                TextBox txt = sender as TextBox;
                txt.TextChanged += new TextChangedEventHandler(txt_TextChanged);
            }
        }

        private static void txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txt = sender as TextBox;

            var bindingExpression = txt.GetBindingExpression(TextBox.TextProperty);
            if (bindingExpression != null)
            {
                bindingExpression.UpdateSource();
            }
        }
    }
}
